import React, {useEffect, useRef, useState} from "react";
import {SuperSelect} from "../../components/SuperSelect";
import Panel from "../../components/Panel";
import {Button, notification, Select, Checkbox} from "antd";
import {HttpGet, HttpPost, Get} from "../../utils/httpUtil";
import "./index.less";
import {Controlled as CodeMirror} from "react-codemirror2";
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/lib/codemirror.js';
import 'codemirror/addon/display/fullscreen.js';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/fold/foldgutter.css';
import 'codemirror/addon/fold/foldcode.js';
import 'codemirror/addon/fold/foldgutter.js';
import 'codemirror/addon/fold/brace-fold.js';
import 'codemirror/addon/fold/comment-fold.js';
import 'codemirror/addon/edit/matchbrackets';
import "codemirror/addon/edit/closebrackets";
// import 'codemirror/addon/hint/show-hint';
import '../../utils/show-hint';
// import 'codemirror/addon/hint/javascript-hint';
import '../../utils/js-hint';
import {toSearchParams} from "../../utils";

function JsEdit(props) {

    const {location} = props;

    const editorRef = useRef();
    const [content, setContent] = useState("");
    const [selectName, setSelectName] = useState();
    const [allRules, setAllRules] = useState([]);
    const [autoComplete, setAutoComplete] = useState(false);
    const autoCompleteRef = useRef(false);

    function saveRule() {
        (async () => {
            if (selectName == null || selectName === "") {
                notification.error({message: "保存规则失败", description: `请先选择规则，暂不支持新增`});
                return
            }
            await HttpPost(`/saveJs`, {
                name: selectName,
                content
            }).then(json => {
                console.log('saveJs:', selectName, content);
                if (json.isSuccess) {
                    notification.success({message: "保存规则成功", description: "保存规则成功"});
                } else {
                    notification.error({message: "保存规则失败", description: `保存规则失败!\nErrorMsg: ${json.errorMsg}`});
                }
            }).catch(err => {
                notification.error({message: "保存规则失败", description: `保存规则失败,无法连接到「APP」!\n${err}`});
            });
        })();
    }

    function onJsSelect(name) {
        setSelectName(name);
        (async () => {
            await Get(`/getJsContent?name=${name}`).then(text => {
                setContent(text);
            }).catch(err => {
                notification.error({message: "获取规则失败", description: `获取规则失败,无法连接到「APP」!\n${err}`});
            });
        })();
    }

    function onCursorActivity(editor) {
        if (autoCompleteRef.current) {
            editor.showHint();
        }
    }

    useEffect(() => {
        const params = toSearchParams(location);
        try {
            const name = params.get("name");
            if (name != null && name.length > 0) {
                onJsSelect(name);
            }
        } catch (e) {
        }
    }, [location]);

    useEffect(() => {
        autoCompleteRef.current = autoComplete;
    }, [autoComplete]);

    useEffect(() => {
        (async () => {
            await HttpGet(`/getAllJsTitles`).then(json => {
                if (json != null && json.length > 0) {
                    setAllRules(json);
                }
            }).catch(err => {
                notification.error({message: "获取规则失败", description: `获取规则失败,无法连接到「APP」!\n${err}`});
            });
        })();
    }, []);

    useEffect(() => {
        const auto = localStorage.getItem("autoComplete");
        if (auto != null && auto === "true") {
            setAutoComplete(true);
        }
    }, []);

    const codeMirrorOpt = {
        lineNumbers: true,
        lineWrapping: true,
        smartIndent: true,
        mode: {name: "javascript"},
        matchBrackets: true,
        autoCloseBrackets: true,
        showHint: true,
        indentWithTabs: true,
        extraKeys: {Tab: 'autocomplete'},
        hintOptions: {
            completeSingle: false,
        },
    };

    return (
        <div className={"js-edit-bg"}>
            <div style={{
                width: 120,
                overflow: 'auto',
                height: '100vh',
                position: 'fixed',
                right: 0,
                marginRight: 20
            }}>
                <div style={{marginBottom: 10}}><Button type={"primary"} onClick={saveRule}>保存规则</Button></div>
            </div>
            <div style={{marginRight: 120}}>

                <div className={"mail-edit-head-bg"}>
                    <h3 className={"head-title"}>选择插件：</h3>
                    <SuperSelect
                        optionFilterProp="children"
                        showSearch={true}
                        dropdownMatchSelectWidth={false}
                        className={"super-select"}
                        value={selectName}
                        onSelect={onJsSelect}>
                        {allRules.map(rule => <Select.Option value={rule}>{rule}</Select.Option>)}
                    </SuperSelect>
                </div>

                <Panel title='编辑插件' titleIcon='api' subTitle={<span>Tips：按Tab键可以自动补全代码
                    <Checkbox checked={autoComplete} onChange={e => {
                        localStorage.setItem("autoComplete", e.target.checked + "");
                        setAutoComplete(e.target.checked);
                    }}
                              style={{marginLeft: 10}}>动态补全</Checkbox></span>}>
                    <div style={{padding: 15}}>
                        <div className={"mail-edit-head-bg"}>
                            <div className={"code-mirror-bg"}>
                                <CodeMirror
                                    onCursorActivity={onCursorActivity}
                                    className={"code-mirror"}
                                    value={content}
                                    options={codeMirrorOpt}
                                    onBeforeChange={(editor, data, value) => setContent(value)}
                                    editorDidMount={editor => {
                                        editorRef.current = editor;
                                    }}
                                />
                            </div>
                        </div>
                    </div>
                </Panel>
            </div>
        </div>
    )
}

export default JsEdit;
